export default {
	namespaced:true,
	// 模块的state数据
	state:() => ({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下6个属性
		// {goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	
	mutations:{
		addToCart(state,goods){
			// 调用find方法 循环数组的每一项x  用x的goods_id与外界传过来的goods_id相比较
		const fResult = state.cart.find(x => x.goods_id === goods.goods_id)

		if(!fResult){
			state.cart.push(goods)
		} else {
			fResult.goods_count ++
		}
		this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state){
			// 将一个数组转换成字符串后存储在本地 修改或者push后都要调用这个方法
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		upDategoodsState(state,goods){
			// 调用find方法 循环数组的每一项x  用x的goods_id与外界传过来的goods_id相比较
			const fResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(fResult){
				fResult.goods_state =goods.goods_state
					this.commit('m_cart/saveToStorage')
			}
		},
		// 更新商品的数量
		upDategoodsCount(state,goods){
			// 调用find方法 循环数组的每一项x  用x的goods_id与外界传过来的goods_id相比较
			const fResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(fResult){
				fResult.goods_count =goods.goods_count
					this.commit('m_cart/saveToStorage')
			}
		},
		// 根据id删除对应的商品
		removeGoodsByID(state,goods_id){
		state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			this.commit('m_cart/saveToStorage')
		}
		,
		// 更新所有商品的勾选状态
		updateAllGoodsState(state,newState){
			// 循环更新购物车中每件商品的勾选状态
			state.cart.forEach(x => x.goods_state = newState)
			// 持久化存储到本地
			this.commit('m_cart/saveToStorage')
		}
	},
	
	getters:{
		//定义一个total方法 用来统计购物车中商品的总数量
		total(state){
			// let c = 0
			// state.cart.forEach(x => c += x.goods_count)
			// return c
			// 下面这个方法reduce初始值0就相当于这个let c =0
		return	state.cart.reduce((total,item) =>  total += item.goods_count,0)
			
		},
		checkedCount(state){
			// state.cart.filter(x => x.goods_state).reduce((total,item) => {return total += item.goods_count},0)
			return	state.cart.filter(x => x.goods_state).reduce((total,item) =>  total += item.goods_count,0)
		},
		// 已经勾选商品到的总价格
		checkedGoodsAmount(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item) =>  total += item.goods_count * item.goods_price,0).toFixed(2)
		}
	}
	
}

